const puppeteer = require('puppeteer');
const path = require('path');

let cached = null;
let deCached = null;

const args = [
  '--no-sandbox',
  '--disable-setuid-sandbox',
  `--window-size=${1920},${1200}`,
  '--lang=en',
  // '--proxy-server=127.0.0.1:1087'
]
/**
 *
 * @param {boolean} de is 德国
 */
async function launch(de) {
  const ip = getIPAdress();
  console.info(`ip=>${ip}`)
  if (!de || ip != '185.188.6.133') {
    if (!cached) {
      cached = await puppeteer.launch({
        // headless: false,
        args,
        userDataDir: path.resolve('./en-profile'),
        defaultViewport: { width: 1920, height: 1200 },
      });
    }
    return cached
  }

  if (!deCached) {
    console.info(`create de browser`)
    deCached = await puppeteer.launch({
      // headless: false,
      args,
      userDataDir: path.resolve('./de-profile'),
      defaultViewport: { width: 1920, height: 1200 },
    });
  }
  return deCached;
}
exports.launch = launch;


async function close() {
  if (cached) {
    await cached.close();
  }
  if (deCached) {
    await deCached.close();
  }
}
exports.close = close;
/**
 *
 * @param {import("puppeteer").Browser} browser
 * @param {string|undefined} url
 */
async function newPage(browser, url) {
  let page = await browser.newPage();
  if (url) await page.goto(url);
  return page;
}
exports.newPage = newPage;

/**
 *
 * @param {number} time time in seconds
 */
async function sleep(time = 2) {
  return new Promise(r => {
    setTimeout(() => {
      r();
    }, time * 1000);
  })
}
exports.sleep = sleep;

/**
 *
 * @param {import("puppeteer").Page} page
 * @param {*} selector
 */
async function click(page, selector) {
  try {
    await page.click(selector)
    console.info('clicker')
  } catch (error) {
    setTimeout(() => {
      click(page, selector)
    }, 1000);
  }
}
exports.click = click;


function getIPAdress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}
